package com.ruoyi.project.system.user.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.ruoyi.common.utils.GoogleAuthenticatorUtils;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.project.channel.businessInfo.domain.BusinessInfo;
import com.ruoyi.project.channel.businessInfo.service.IBusinessInfoService;
import com.ruoyi.project.channel.channelScore.domain.ChannelScore;
import com.ruoyi.project.channel.channelScore.service.IChannelScoreService;
import com.ruoyi.project.channel.channelScoreSetting.domain.ChannelScoreSetting;
import com.ruoyi.project.channel.channelScoreSetting.service.IChannelScoreSettingService;
import com.ruoyi.project.channel.channelUserInfo.domain.ChannelUserInfo;
import com.ruoyi.project.channel.channelUserInfo.service.IChannelUserInfoService;
import com.ruoyi.project.channel.clickFormUser.domain.ClickFormUser;
import com.ruoyi.project.channel.salesmanInfo.domain.SalesmanInfo;
import com.ruoyi.project.channel.salesmanInfo.service.ISalesmanInfoService;
import com.ruoyi.project.channel.smsInfo.service.ISmsInfoService;
import com.ruoyi.project.pay.InvitationCodeGenerator;
import com.ruoyi.project.pay.PayConfig;
import com.ruoyi.project.system.dept.domain.Dept;
import com.ruoyi.project.system.dept.service.IDeptService;
import com.ruoyi.project.system.role.domain.Role;
import com.ruoyi.project.system.user.domain.UserRole;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.system.post.service.IPostService;
import com.ruoyi.project.system.role.service.IRoleService;
import com.ruoyi.project.system.user.domain.User;
import com.ruoyi.project.system.user.service.IUserService;

/**
 * 用户信息
 *
 * @author ruoyi
 */
@Controller
@RequestMapping("/system/user")
public class UserController extends BaseController {
    private String prefix = "system/user";

    @Autowired
    private IUserService userService;

    @Autowired
    private IRoleService roleService;
    @Autowired
    private IDeptService deptService;
    @Autowired
    private IPostService postService;
    @Autowired
    private IBusinessInfoService businessInfoService;
    @Autowired
    private ISmsInfoService smsInfoService;
    @Autowired
    private IChannelUserInfoService channelUserInfoService;
    @Autowired
    private IChannelScoreService channelScoreService;
    @Autowired
    private IChannelScoreSettingService channelScoreSettingService;
    @Autowired
    private PayConfig payConfig;
    @Autowired
    private InvitationCodeGenerator invitationCodeGenerator;
    @Autowired
    private ISalesmanInfoService salesmanInfoService;

    @RequiresPermissions("system:user:view")
    @GetMapping()
    public String user(ModelMap mmap) {
        Dept search = new Dept();
        search.setParentId(100L);
        List<Dept> depts = deptService.selectDeptList(search);
        mmap.put("depts", depts);
        return prefix + "/user";
    }

    /**
     * 把没必要显示给用户看的字段屏蔽掉
     *
     * @param users
     */
    private void resetUserList(List<User> users) {
        for (int s = 0; s < users.size(); s++) {
            User tmpUs = users.get(s);
            tmpUs.setPassword(null);
            tmpUs.setSecretKey(null);
            tmpUs.setLoginIp(null);
            tmpUs.setPhonenumber(null);
            tmpUs.setSalt(null);
        }
    }

    @RequiresPermissions("system:user:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(User user) {
        startPage();
        String roleKey = ShiroUtils.getSysUser().getRoles().get(0).getRoleKey();
        if (roleKey.equals("agent")) {
            user.setUserId(ShiroUtils.getSysUser().getUserId());
        } else if (roleKey.equals("salesman")) {
            user.setUserId(ShiroUtils.getSysUser().getUserId());
        } else if (roleKey.equals("group")) {
            // 组长
            user.getParams().put("groupUserId", ShiroUtils.getSysUser().getUserId());
        }
        List<User> list = userService.selectUserList(user);
        resetUserList(list);
        Long[] ids = new Long[list.size()];
        for (int i = 0; i < list.size(); i++) {
            ids[i] = list.get(i).getUserId();
        }
        if (ids.length > 0) {
            // 获取角色为商户的用户
            List<UserRole> userRoles = userService.selectUserRoleListByIds(ids);
            for (int j = 0; j < userRoles.size(); j++) {
                UserRole userRole = userRoles.get(j);
                for (int i = 0; i < list.size(); i++) {
                    User user1 = list.get(i);
                    if (user1.getUserId().longValue() == userRole.getUserId().longValue()) {
                        user1.setRoleId(userRole.getRoleId());
                        break;
                    }
                }
            }
        }
        return getDataTable(list);
    }

    @RequiresPermissions("system:user:list")
    @GetMapping("/list/group/{userId}")
    @ResponseBody
    public AjaxResult getGroupUserList(@PathVariable("userId") Long userId) {
        User search = new User();
        search.getParams().put("salesman", "111"); // 获取所有业务员
        List<User> list = userService.selectUserList(search);
        resetUserList(list);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("all", getDataTable(list));

        search = new User();
        search.getParams().put("groupUserId", userId); // 获取所有业务员
        list = userService.selectUserList(search);
        resetUserList(list);
        jsonObject.put("groupUser", getDataTable(list));
        return AjaxResult.success("success", jsonObject);
    }

    /**
     * 批量更新业务员
     */
    @RequiresPermissions("system:user:list")
    @PostMapping("/updateGroupUser")
    @ResponseBody
    public AjaxResult updateGroupUser(Long groupId, String userIds) {
        String[] ids = userIds.split(",");
        for (String id : ids) {
            SalesmanInfo salesmanInfo = new SalesmanInfo();
            salesmanInfo.setUserId(Long.valueOf(id));
            salesmanInfo.setGroupUserId(groupId);
            salesmanInfoService.updateSalesmanInfo(salesmanInfo);
        }
        return AjaxResult.success("success");
    }

    @RequiresPermissions("system:user:view")
    @GetMapping("/businessList/{userId}")
    public String businessUser(@PathVariable("userId") Long userId, ModelMap mmap) {
        mmap.put("userId", userId + "");
        return prefix + "/business";
    }

    @RequiresPermissions("system:user:view")
    @GetMapping("/scoreList/{userId}")
    public String scoreUser(@PathVariable("userId") Long userId, ModelMap mmap) {
        mmap.put("userId", userId + "");
        return prefix + "/score";
    }

    @RequiresPermissions("system:user:list")
    @PostMapping("/businessList/{userId}")
    @ResponseBody
    public TableDataInfo businessList(User user, @PathVariable("userId") Long userId) {
        startPage();
        user.setUserId(userId);
        List<User> list = userService.selectUserList(user);
        resetUserList(list);
        return getDataTable(list);
    }

    /**
     * 业务员列表
     */
    @RequiresPermissions("system:user:list")
    @PostMapping("/salesman")
    @ResponseBody
    public TableDataInfo salespersonList() {
        startPage();
        User search = new User();
        search.getParams().put("salesman", "true");
        String roleKey = ShiroUtils.getSysUser().getRoles().get(0).getRoleKey();
       if (roleKey.equals("group")) {
            // 组长
           search.getParams().put("groupUserId", ShiroUtils.getSysUser().getUserId());
        }
        List<User> list = userService.selectUserList(search);
        resetUserList(list);
        return getDataTable(list);
    }

    /**
     * 获取所有组长
     */
    @RequiresPermissions("system:user:list")
    @PostMapping("/groupUser")
    @ResponseBody
    public TableDataInfo groupUserList() {
        startPage();
        User search = new User();
        search.getParams().put("groupUser", "true");
        List<User> list = userService.selectUserList(search);
        resetUserList(list);
        return getDataTable(list);
    }

    @RequiresPermissions("system:user:list")
    @PostMapping("/scoreList/{userId}")
    @ResponseBody
    public TableDataInfo scoreList(User user, @PathVariable("userId") Long userId) {
        startPage();
        user.setUserId(null);
        user.getParams().put("scoreId", userId);
        List<User> list = userService.selectUserList(user);
        resetUserList(list);
        return getDataTable(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @RequiresPermissions("system:user:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(User user) {
        List<User> list = userService.selectUserList(user);
        resetUserList(list);
        ExcelUtil<User> util = new ExcelUtil<User>(User.class);
        return util.exportExcel(list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @RequiresPermissions("system:user:import")
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<User> util = new ExcelUtil<User>(User.class);
        List<User> userList = util.importExcel(file.getInputStream());
        String message = userService.importUser(userList, updateSupport);
        return AjaxResult.success(message);
    }

    @RequiresPermissions("system:user:view")
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate() {
        ExcelUtil<User> util = new ExcelUtil<User>(User.class);
        return util.importTemplateExcel("用户数据");
    }

    /**
     * 新增用户
     */
    @GetMapping("/add")
    public String add(ModelMap mmap) {
        mmap.put("roles", roleService.selectRoleAll());
        mmap.put("posts", postService.selectPostAll());
        return prefix + "/add";
    }

    /**
     * 新增商户
     */
    @GetMapping("/addBusiness")
    public String addBusiness(ModelMap mmap) {
        mmap.put("posts", postService.selectPostAll());
        // 获取所有代理信息
        mmap.put("proxys", userService.getAgentUsers());
        // 获取所有渠道商
        mmap.put("channels", userService.selectChannelList(new User()));
        Role searchRole = new Role();
        searchRole.setRoleKey("mall");
        mmap.put("roles", roleService.selectRoleList(searchRole));
        return prefix + "/addBusiness";
    }

    /**
     * 新增支付商
     */
    @GetMapping("/addPayer")
    public String addPayer(ModelMap mmap) {
        mmap.put("posts", postService.selectPostAll());
        Role searchRole = new Role();
        searchRole.setRoleKey("payer");
        mmap.put("roles", roleService.selectRoleList(searchRole));
        return prefix + "/addPayer";
    }

    /**
     * 新增支付商
     */
    @GetMapping("/addSuper")
    public String addSuper(ModelMap mmap) {
        mmap.put("posts", postService.selectPostAll());
        Role searchRole = new Role();
        searchRole.setRoleKey("admin2");
        mmap.put("roles", roleService.selectRoleList(searchRole));
        return prefix + "/addSuper";
    }

    /**
     * 新增支付商
     */
    @GetMapping("/addSalesman")
    public String addSalesman(ModelMap mmap) {
        mmap.put("posts", postService.selectPostAll());
        Role searchRole = new Role();
        searchRole.setRoleKey("salesman");
        mmap.put("roles", roleService.selectRoleList(searchRole));
        return prefix + "/addSalesman";
    }

    /**
     * 新增支付商
     */
    @GetMapping("/addChannel")
    public String addChannel(ModelMap mmap) {
        mmap.put("posts", postService.selectPostAll());
        Role searchRole = new Role();
        searchRole.setRoleKey("channel");
        mmap.put("roles", roleService.selectRoleList(searchRole));
        return prefix + "/addChannel";
    }

    /**
     * 新增支付商
     */
    @GetMapping("/addScore/{pid}")
    public String addScore(ModelMap mmap, @PathVariable("pid") Long pid) {
        mmap.put("posts", postService.selectPostAll());
        Role searchRole = new Role();
        searchRole.setRoleKey("score");
        mmap.put("roles", roleService.selectRoleList(searchRole));
        mmap.put("pid", pid);
        BigDecimal bigDecimal = null;
        if (1 == pid.longValue()) {
            ChannelScoreSetting setting = channelScoreSettingService.selectChannelScoreSettingById(1L);
            bigDecimal = setting.getRate();
            mmap.put("level", "1");
        } else {
            ChannelScore channelScore = channelScoreService.selectChannelScoreById(pid);
            bigDecimal = channelScore.getRate();
            mmap.put("level", channelScore.getLevel() + 1);
        }
        mmap.put("prate", bigDecimal);
        return prefix + "/addScore";
    }

    /**
     * 新增代理
     */
    @GetMapping("/addProxy")
    public String addProxy(ModelMap mmap) {
        mmap.put("posts", postService.selectPostAll());
        Role searchRole = new Role();
        searchRole.setRoleKey("agent");
        mmap.put("roles", roleService.selectRoleList(searchRole));
        return prefix + "/addProxy";
    }

    /**
     * 新增保存用户
     */
    @RequiresPermissions("system:user:add")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(User user) {
        if (StringUtils.isNotNull(user.getUserId()) && User.isAdmin(user.getUserId())) {
            return error("不允许修改超级管理员用户");
        }
        return toAjax(userService.insertUser(user));
    }

    /**
     * 新增保存用户
     */
    @RequiresPermissions("system:user:addBusiness")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping("/addBusiness")
    @ResponseBody
    public AjaxResult addSaveBusiness(User user, BusinessInfo businessInfo) {
        if (StringUtils.isNotNull(user.getUserId()) && User.isAdmin(user.getUserId())) {
            return error("不允许修改超级管理员用户");
        }
        // 如果是代理商, 添加的商户默认加上归属代理商信息
        userService.insertUser(user);
        businessInfo.setBusinessType("0");
        if (ShiroUtils.getSysUser().getRoles().get(0).getRoleName().equals("agent")) {
            businessInfo.setParentUserId(ShiroUtils.getSysUser().getUserId());
        }
        return toAjax(businessInfoService.insertBusinessInfo(businessInfo, user));
    }

    /**
     * 新增保存用户
     */
    @RequiresPermissions("system:user:add")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping("/addSaveSalesman")
    @ResponseBody
    public AjaxResult addSaveSalesman(User user) {
        if (StringUtils.isNotNull(user.getUserId()) && User.isAdmin(user.getUserId())) {
            return error("不允许修改超级管理员用户");
        }
        // 如果是代理商, 添加的商户默认加上归属代理商信息
        return toAjax(userService.insertUser(user));
    }

    /**
     * 新增保存用户
     */
    @RequiresPermissions("system:user:addBusiness")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping("/addChannel")
    @ResponseBody
    public AjaxResult addSaveChannel(User user) {
        if (StringUtils.isNotNull(user.getUserId()) && User.isAdmin(user.getUserId())) {
            return error("不允许修改超级管理员用户");
        }
        // 如果是代理商, 添加的商户默认加上归属代理商信息
        userService.insertUser(user);
        return toAjax(channelUserInfoService.insertChannelUserInfo(new ChannelUserInfo(), user));
    }

    /**
     * 新增保存用户
     */
    @RequiresPermissions("system:user:addProxy")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping("/addProxy")
    @ResponseBody
    public AjaxResult addSaveProxy(User user, Long groupUser) {
        if (StringUtils.isNotNull(user.getUserId()) && User.isAdmin(user.getUserId())) {
            return error("不允许修改超级管理员用户");
        }
        String roleKey = ShiroUtils.getSysUser().getRoles().get(0).getRoleKey();


        user.setRemark(invitationCodeGenerator.generateUniqueCode());
        userService.insertUser(user);
        SalesmanInfo salesmanInfo = new SalesmanInfo();
        salesmanInfo.setUserId(user.getUserId());
        if (roleKey.equals("group")) {
            // 组长
            salesmanInfo.setGroupUserId(ShiroUtils.getSysUser().getUserId());
        } else {
            salesmanInfo.setGroupUserId(groupUser);
        }
        return toAjax(salesmanInfoService.insertSalesmanInfo(salesmanInfo));
    }

    /**
     * 新增保存用户
     */
    @RequiresPermissions("system:user:addBusiness")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping("/addScore/{pid}")
    @ResponseBody
    public AjaxResult addSaveScore(User user, ChannelScore channelScore, @PathVariable("pid") Long pid) {
        if (StringUtils.isNotNull(user.getUserId()) && User.isAdmin(user.getUserId())) {
            return error("不允许修改超级管理员用户");
        }
        // 如果是代理商, 添加的商户默认加上归属代理商信息
        BigDecimal rate;
        int level = 1;
        if (1 == pid.longValue()) {
            ChannelScoreSetting setting = channelScoreSettingService.selectChannelScoreSettingById(1L);
            rate = setting.getRate();
        } else {
            ChannelScore pScore = channelScoreService.selectChannelScoreById(pid);
            rate = pScore.getRate();
            level = pScore.getLevel() + 1;
        }
        if (rate.compareTo(channelScore.getRate()) == -1) {
            // 父级代理的费率必须大于 自己代理
            return error("费率超过规定范围，请重新输入");
        }
        userService.insertUser(user);
        channelScore.setUserId(user.getUserId());
        channelScore.setPid(pid);
        channelScore.setLevel(level);
        channelScore.setCreateBy(ShiroUtils.getSysUser().getUserName());
        channelScore.setCreateTime(new Date());
        return channelScoreService.insertChannelScore(channelScore, user);
    }


    /**
     * 修改用户
     */
    @GetMapping("/edit/{userId}")
    public String edit(@PathVariable("userId") Long userId, ModelMap mmap) {
        mmap.put("user", userService.selectUserById(userId));
        mmap.put("roles", roleService.selectRolesByUserId(userId));
        mmap.put("posts", postService.selectPostsByUserId(userId));
        return prefix + "/edit";
    }

    /**
     * 修改用户
     */
    @GetMapping("/editBusiness/{userId}")
    public String editBusiness(@PathVariable("userId") Long userId, ModelMap mmap) {
        User user = userService.selectUserById(userId);
        user.setSecretKey("");
        user.setSalt("");
        user.setPassword("");
        mmap.put("proxys", userService.getAgentUsers());
        mmap.put("user", user);
        mmap.put("business", businessInfoService.selectBusinessInfoByUserId(userId));
        // 获取所有渠道商
        mmap.put("channels", userService.selectChannelList(new User()));
        mmap.put("posts", postService.selectPostsByUserId(userId));
        Role searchRole = new Role();
        searchRole.setRoleKey("mall");
        mmap.put("roles", roleService.selectRoleList(searchRole));
        return prefix + "/editBusiness";
    }

    /**
     * 修改用户
     */
    @GetMapping("/getBusiness/{userId}")
    @ResponseBody
    public AjaxResult getBusinessInfo(@PathVariable("userId") Long userId) {
        HashMap<String, Object> mmap = new HashMap<>();
        User user = userService.selectUserById(userId);
        user.setSecretKey("");
        user.setSalt("");
        user.setPassword("");
        List<User> proxys = userService.getAgentUsers();
        resetUserList(proxys);
        mmap.put("proxys", proxys);
        mmap.put("user", user);
        BusinessInfo businessInfo = businessInfoService.selectBusinessInfoByUserId(userId);
        businessInfo.setPayPwd("");
        mmap.put("business", businessInfo);
        // 获取所有渠道商
        List<User> channels = userService.selectChannelList(new User());
        resetUserList(channels);
        mmap.put("channels", channels);
        mmap.put("posts", postService.selectPostsByUserId(userId));
        Role searchRole = new Role();
        searchRole.setRoleKey("mall");
        mmap.put("roles", roleService.selectRoleList(searchRole));
        return AjaxResult.success("success", mmap);
    }

    /**
     * 修改用户
     */
    @GetMapping("/business/{userId}")
    @ResponseBody
    public AjaxResult getBusiness(@PathVariable("userId") Long userId) {
        HashMap<String, Object> mmap = new HashMap<>();
        mmap.put("proxys", userService.getAgentUsers());
        mmap.put("user", userService.selectUserById(userId));
        mmap.put("business", businessInfoService.selectBusinessInfoByUserId(userId));
        // 获取所有渠道商
        mmap.put("channels", userService.selectChannelList(new User()));
        mmap.put("posts", postService.selectPostsByUserId(userId));
        Role searchRole = new Role();
        searchRole.setRoleKey("mall");
        mmap.put("roles", roleService.selectRoleList(searchRole));
        return AjaxResult.success("success", mmap);
    }

    /**
     * 修改用户
     */
    @GetMapping("/editProxy/{userId}")
    public String editProxy(@PathVariable("userId") Long userId, ModelMap mmap) {
        mmap.put("user", userService.selectUserById(userId));
        Role searchRole = new Role();
        searchRole.setRoleKey("agent");
        mmap.put("roles", roleService.selectRoleList(searchRole));
        mmap.put("posts", postService.selectPostsByUserId(userId));
        return prefix + "/editProxy";
    }

    /**
     * 修改用户
     */
    @GetMapping("/editPayer/{userId}")
    public String editPayer(@PathVariable("userId") Long userId, ModelMap mmap) {
        mmap.put("user", userService.selectUserById(userId));
        Role searchRole = new Role();
        searchRole.setRoleKey("payer");
        mmap.put("roles", roleService.selectRoleList(searchRole));
        mmap.put("posts", postService.selectPostsByUserId(userId));
        return prefix + "/editProxy";
    }

    /**
     * 修改用户
     */
    @GetMapping("/editSalesman/{userId}")
    public String editSalesman(@PathVariable("userId") Long userId, ModelMap mmap) {
        mmap.put("user", userService.selectUserById(userId));
        Role searchRole = new Role();
        searchRole.setRoleKey("salesman");
        mmap.put("roles", roleService.selectRoleList(searchRole));
        mmap.put("posts", postService.selectPostsByUserId(userId));
        return prefix + "/editSalesman";
    }

    /**
     * 修改用户
     */
    @GetMapping("/editChannel/{userId}")
    public String editChannel(@PathVariable("userId") Long userId, ModelMap mmap) {
        mmap.put("user", userService.selectUserById(userId));
        Role searchRole = new Role();
        searchRole.setRoleKey("channel");
        mmap.put("roles", roleService.selectRoleList(searchRole));
        mmap.put("posts", postService.selectPostsByUserId(userId));
        return prefix + "/editChannel";
    }


    /**
     * 修改用户
     */
    @GetMapping("/editScore/{userId}")
    public String editScore(@PathVariable("userId") Long userId, ModelMap mmap) {
        mmap.put("user", userService.selectUserById(userId));
        ChannelScore channelScore = channelScoreService.selectChannelScoreById(userId);
        mmap.put("channelScore", channelScore);
        if (1L == channelScore.getPid().longValue()) {
            ChannelScoreSetting setting = channelScoreSettingService.selectChannelScoreSettingById(1L);
            mmap.put("parentPhoneNum", "总代");
            mmap.put("parentQQNum", "总代");
            mmap.put("prate", setting.getRate());
        } else {
            ChannelScore parentChannelScore = channelScoreService.selectChannelScoreById(channelScore.getPid());
            User parentUser = userService.selectUserById(channelScore.getPid());
            mmap.put("parentPhoneNum", parentUser.getPhonenumber());
            mmap.put("parentQQNum", parentChannelScore.getQq());
            mmap.put("prate", parentChannelScore.getRate());
        }

        Role searchRole = new Role();
        searchRole.setRoleKey("score");
        mmap.put("roles", roleService.selectRoleList(searchRole));
        mmap.put("posts", postService.selectPostsByUserId(userId));
        return prefix + "/editScore";
    }

    /**
     * 修改保存用户
     */
    @RequiresPermissions("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(User user) {
        if (StringUtils.isNotNull(user.getUserId()) && User.isAdmin(user.getUserId())) {
            return error("不允许修改超级管理员用户");
        }
        return toAjax(userService.updateUser(user));
    }

    /**
     * 修改保存用户
     */
    @RequiresPermissions("system:user:editBusiness")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/editBusiness")
    @ResponseBody
    public AjaxResult editSaveBusiness(User user, BusinessInfo businessInfo) {
        // 如果是代理商, 添加的商户默认加上归属代理商信息
        userService.updateUserInfo(user);
        if (ShiroUtils.getSysUser().getRoles().get(0).getRoleName().equals("agent")) {
            businessInfo.setParentUserId(ShiroUtils.getSysUser().getUserId());
        }
        BusinessInfo info = businessInfoService.selectBusinessInfoById(businessInfo.getBusinessId());
        info.setParentUserId(businessInfo.getParentUserId());
        info.setChannelUserId(businessInfo.getChannelUserId());
        info.setChannelRate(businessInfo.getChannelRate());
        info.setApiKey(businessInfo.getApiKey());
        return toAjax(businessInfoService.updateBusinessInfo(info));
    }

    /**
     * 修改跑分用户
     */
    @RequiresPermissions("system:user:editBusiness")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/editScore")
    @ResponseBody
    public AjaxResult editSaveScore(User user, ChannelScore channelScore) {
        // 只能编辑qq号
        userService.updateUserInfo(user);
        return channelScoreService.updateChannelScore(channelScore, user);
    }

    @RequiresPermissions("system:user:resetPayPwd")
    @Log(title = "重置密码", businessType = BusinessType.UPDATE)
    @PostMapping("/resetPayPwd")
    @ResponseBody
    public AjaxResult resetPayPwd(User user) {

        return toAjax(userService.resetUserPwd(user));
    }

    @RequiresPermissions("system:user:resetPwd")
    @Log(title = "重置密码", businessType = BusinessType.UPDATE)
    @PostMapping("/resetPwd")
    @ResponseBody
    public AjaxResult resetPwd(User user, String code) {
        User user1 = userService.selectUserById(ShiroUtils.getSysUser().getUserId());
//        boolean b = smsInfoService.validateCode(user1.getPhonenumber(), code.trim());
//        boolean b = smsInfoService.validateCode(user1.getEmail().trim(), code.trim());
//        if (!b) {
//            return AjaxResult.error("手机验证码出错！");
//        }
        User tmp = userService.selectUserById(user.getUserId());
        user.setLoginName(tmp.getLoginName());
        return toAjax(userService.resetUserPwd(user));
    }

    @RequiresPermissions("system:user:remove")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        try {
            return toAjax(userService.deleteUserByIds(ids));
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    /**
     * 校验用户名
     */
    @PostMapping("/checkLoginNameUnique")
    @ResponseBody
    public String checkLoginNameUnique(User user) {
        return userService.checkLoginNameUnique(user.getLoginName());
    }

    /**
     * 校验手机号码
     */
    @PostMapping("/checkPhoneUnique")
    @ResponseBody
    public String checkPhoneUnique(User user) {
        return userService.checkPhoneUnique(user);
    }

    /**
     * 校验email邮箱
     */
    @PostMapping("/checkEmailUnique")
    @ResponseBody
    public String checkEmailUnique(User user) {
        return userService.checkEmailUnique(user);
    }

    /**
     * 用户状态修改
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @RequiresPermissions("system:user:edit")
    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(User user) {
        return toAjax(userService.changeStatus(user));
    }

    /**
     * 修改用户
     */
    @GetMapping("/bindGoogle")
    public String bindingGoogleAuth(ModelMap mmap) {
        //服务名称(一般定义为常量) 如 Google Github 印象笔记 等(不参与运算,只是为了与其他服务作区分)
        String issuer = payConfig.getTitle();
        //获取用户名称(从数据库或者缓存),可以是登录名,邮箱,手机(不参与运算,只是为了与其他服务作区分)
        String account = ShiroUtils.getLoginName();
        //生成密钥,并保存到数据库
        User curUser = userService.selectUserById(ShiroUtils.getUserId());
        String secretKey = curUser.getSecretKey();
        if (secretKey == null || "".equals(secretKey)) {
            secretKey = GoogleAuthenticatorUtils.createSecretKey();
        } else {
            //
            return prefix + "/profile/googleUnBind";
        }
        //生成二维码信息
        String googleAuthQRCodeData = GoogleAuthenticatorUtils.createGoogleAuthQRCodeData(secretKey, account + "", issuer);
        mmap.put("googleAuthQRCodeData", googleAuthQRCodeData);
        mmap.put("secretKey", secretKey);
        return prefix + "/profile/google";
    }

    /**
     * 修改用户
     */
    @GetMapping("/hasBindGoogle")
    @ResponseBody
    public AjaxResult getHasBindGoole() {
        User curUser = userService.selectUserById(ShiroUtils.getUserId());
        String secretKey = curUser.getSecretKey();
        if (secretKey == null || "".equals(secretKey)) {
            String issuer = payConfig.getTitle();
            //获取用户名称(从数据库或者缓存),可以是登录名,邮箱,手机(不参与运算,只是为了与其他服务作区分)
            String account = ShiroUtils.getLoginName();
            secretKey = GoogleAuthenticatorUtils.createSecretKey();
            String googleAuthQRCodeData = GoogleAuthenticatorUtils.createGoogleAuthQRCodeData(secretKey, account + "", issuer);
            HashMap<String, String> mmap = new HashMap<>();
            mmap.put("googleAuthQRCodeData", googleAuthQRCodeData);
            mmap.put("secretKey", secretKey);
            return AjaxResult.success("success", mmap);

        } else {
            //
            return AjaxResult.success("success", true);
        }
    }

    /**
     * 确认绑定
     */
    @Log(title = "绑定谷歌", businessType = BusinessType.UPDATE)
    @PostMapping("/bindGoogle")
    @ResponseBody
    public AjaxResult bindingGoogleAuth(String code, String secretKey) {
        //根据用户信息从数据库中获取保存时的密钥
        if (secretKey == null || "".equals(secretKey)) {
            return error("操作出错，请重新退出系统再登录重试！");
        }
        if (code == null || "".equals(code)) {
            return error("请输入code！");
        }
        boolean success = GoogleAuthenticatorUtils.verify(secretKey, code);
        if (success) {
            User user = new User();
            user.setUserId(ShiroUtils.getUserId());
            user.setSecretKey(secretKey);
            userService.updateUserSecretKey(user);
            //设置用户开启二步验证,更新用户信息
            //生成备用验证码,保存到数据库,同时返回到前台显示,并提示用户进行保存
            //在用户手机丢失后,或者APP,验证信息被误删,可以通过使用备用验证码的方式进行登录
            return success("绑定成功");
        }
        return error("绑定失败");
    }

    /**
     * 确认绑定
     */
    @Log(title = "解除绑定", businessType = BusinessType.UPDATE)
    @PostMapping("/unBindGoogle")
    @ResponseBody
    public AjaxResult unBindGoogleAuth(String code) {
        //根据用户信息从数据库中获取保存时的密钥
        if (code == null || "".equals(code)) {
            return error("请输入code！");
        }
        User curUser = userService.selectUserById(ShiroUtils.getUserId());
        String secretKey = curUser.getSecretKey();
        if (secretKey == null || "".equals(secretKey)) {
            return error("异常操作！");
        }
        boolean success = GoogleAuthenticatorUtils.verify(secretKey, code);
        if (success) {
            User user = new User();
            user.setUserId(ShiroUtils.getUserId());
            user.setSecretKey("");
            userService.updateUserSecretKey(user);
            //设置用户开启二步验证,更新用户信息
            //生成备用验证码,保存到数据库,同时返回到前台显示,并提示用户进行保存
            //在用户手机丢失后,或者APP,验证信息被误删,可以通过使用备用验证码的方式进行登录
            return success("解除绑定成功");
        }
        return error("解除绑定失败");
    }


    /**
     * 确认绑定
     */
    @GetMapping("/needBinding")
    @ResponseBody
    public AjaxResult unBindGoogleAuth() {
        User user = userService.selectUserById(ShiroUtils.getUserId());
        if (user.getPhonenumber() == null || user.getPhonenumber().trim().equals("")) {
            return AjaxResult.error("need binding");
        }
        return AjaxResult.success("normal");
    }
}